<template>
  <a-upload
      v-model:file-list="list"
      :multiple="true"
      :headers="headers"
      :action="action"
      list-type="picture-card"
      @preview="handlePreview"
      :before-upload="beforeUpload"
  >
    <div>
      <plus-outlined />
      <div style="margin-top: 8px">上传</div>
    </div>
  </a-upload>
  <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancels">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>
<script setup>
import {ref} from "vue";
import {getToken} from "@utils/storage.js";
import {message, Upload} from "ant-design-vue";
const props = defineProps({
  action:{
    type:String,
  },
})
const list = defineModel('list')
const previewImage = ref('');
const previewTitle = ref('');
const headers = ref({
  "X-Access-Token":getToken()
})
const previewVisible = ref(false)
const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
const handleCancels = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
/**
 * 上传文件预览
 * @param file 文件对象
 * @returns {Promise<void>}
 */
const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
}
/**
 * 上传文件限制
 * @param file
 * @returns {boolean|string}
 */
const beforeUpload = file => {
  if (!['image/jpeg','image/png','image/jpg','image/gif','image/webp'].includes(file.type)) {
    message.error(`${file.name} is not a picture`);
  }
  return ['image/jpeg','image/png','image/jpg','image/gif','image/webp'].includes(file.type) || Upload.LIST_IGNORE
}
</script>
<style scoped>

</style>
